<script setup lang="ts">
import formButton from '@renderer/components/formButton.vue'
import NavBar from '@renderer/components/navBar.vue'
import useExport from '@renderer/composables/useExport'
import helper from '@renderer/utils/helper'
import dayjs from 'dayjs'
import { reactive, ref } from 'vue'
const initParams = () => ({
  startAndEndTime: '',
  limit: 10,
})
const initSubmitForm = () => ({
  startAndEndTime: '',
  email: '',
})
const queryParams = reactive(initParams())
const submitForm = reactive(initSubmitForm())
const currentType = ref<initType>('init')
const exportType = ref('')
const exportDataType = ref('')
const selectDataName = ref([])
const exportDialog = ref(false)
const shopDialog = ref(false)
const exportOptions = [
  {
    value: '1',
    label: '导出账本流水',
  },
  {
    value: '2',
    label: '导出账户流水',
  },
]
const exportDataOptions = ref<{ value: string; label: string }[]>([])

const dataListOptions = ref<{ value: string; label: string }[]>([])
const handleNextPage = async (val: number) => {
  await initData(currentType.value, val)
}
const handleReset = async () => {
  Object.assign(queryParams, initParams())
  currentType.value = 'init'
  await initData('init', 1)
}
const handleQuery = async () => {
  currentType.value = 'search'
  await initData(currentType.value, 1)
}
const initData = async (type: initType, page: number) => {
  const [startTime, endTime] = type == 'init' ? ['', ''] : queryParams.startAndEndTime
  const params = {
    start_time: type == 'init' ? '' : dayjs(startTime).unix(),
    end_time: type == 'init' ? '' : dayjs(endTime).unix(),
    page: page,
    limit: queryParams.limit,
  }
  await getExportRecord(params)
}
const handleShopClose = async () => {
  Object.assign(submitForm, initSubmitForm())
  shopDialog.value = false
  await initData('init', 1)
}
const handleClose = async () => {
  Object.assign(submitForm, initSubmitForm())
  exportType.value = ''
  exportDataType.value = ''
  selectDataName.value = []
  exportDataOptions.value = []
  dataListOptions.value = []
  exportDialog.value = false
  await initData('init', 1)
}
const handleDataExport = () => {
  exportDialog.value = true
}
const handleShopExport = () => {
  shopDialog.value = true
}
const handleExportTypeChange = async (event) => {
  exportDataOptions.value = []
  exportDataType.value = ''
  selectDataName.value = []
  dataListOptions.value = []
  switch (event) {
    case '1':
      exportDataOptions.value = [
        {
          value: '1',
          label: '普通账本',
        },
        {
          value: '2',
          label: '仓库账本',
        },
        {
          value: '3',
          label: '项目账本',
        },
      ]
      break
    case '2':
      const accountList: AccountModel[] = await getBillAccountList()
      accountList.forEach((item: AccountModel) => {
        dataListOptions.value.push({
          value: item.id + '',
          label: item.name + '流水数据',
        })
      })
      break
  }
}
const handleExportDataTypeChange = async (event) => {
  selectDataName.value = []
  dataListOptions.value = []
  switch (event) {
    case '1':
      dataListOptions.value = [
        {
          value: '1',
          label: '公司账本流水数据',
        },
        {
          value: '5',
          label: '意向金账本流水数据',
        },
        {
          value: '3',
          label: '欢乐基金账本流水数据',
        },
        {
          value: '2',
          label: '借支账本流水数据',
        },
        {
          value: '6',
          label: '分红账本流水数据',
        },
      ]
      break
    case '2':
      dataListOptions.value = [
        {
          value: '1',
          label: '仓库账本流水数据',
        },
      ]
      break
    case '3':
      const billList: ApiPage<projectBillModel> = await getProjectBillList()
      billList.data.forEach((item) => {
        dataListOptions.value.push({
          value: item.id + '',
          label: item.name,
        })
      })
  }
}
const handleSave = async () => {
  const [startTime, endTime] = submitForm.startAndEndTime
  switch (exportType.value) {
    case '1':
      await exportData({
        export_type: exportDataType.value,
        export_ids: selectDataName.value.join(','),
        start_time: dayjs(startTime).format('YYYY-MM-DD'),
        end_time: dayjs(endTime).format('YYYY-MM-DD'),
        email: submitForm.email,
      })
      handleClose()
      break
    case '2':
      await accountExportData({
        export_ids: selectDataName.value.join(','),
        start_time: dayjs(startTime).format('YYYY-MM-DD'),
        end_time: dayjs(endTime).format('YYYY-MM-DD'),
        email: submitForm.email,
      })
      handleClose()
      break
  }
}
const handleShopSave = async () => {
  await stashStockExport({
    email: submitForm.email,
  })
  await handleShopClose()
}
const {
  getExportRecord,
  expoetList,
  getProjectBillList,
  getBillAccountList,
  accountExportData,
  exportData,
  stashStockExport,
} = useExport()
const { checkRule, checkCompanyRule } = helper()
await initData('init', 1)
</script>

<template>
  <main class="bg-white flex flex-col gap-3 rounded-md" style="height: -webkit-fill-available">
    <el-form :model="queryParams" inline>
      <el-form-item label="导出时间">
        <!-- <el-date-picker v-model="queryParams.start_time" type="date" placeholder="请选择" /> -->
        <el-date-picker
          v-model="queryParams.startAndEndTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始月份"
          end-placeholder="结束月份" />
      </el-form-item>
      <el-form-item>
        <formButton class="mr-3" @click="handleQuery"> 搜索 </formButton>
        <formButton class="mr-3" @click="handleReset"> 重置 </formButton>
        <formButton
          class="mr-3"
          @click="handleDataExport"
          v-if="checkRule('流水数据导出权') && checkCompanyRule('check_record', 2)">
          流水数据导出
        </formButton>
        <formButton @click="handleShopExport" v-if="checkRule('库存数据导出权')"> 库存数据导出 </formButton>
      </el-form-item>
    </el-form>
    <el-table
      :data="expoetList?.data"
      border
      header-align="center"
      :header-cell-style="{ background: '#FFF4E5', fontSize: '14px', color: '#888', fontWeight: '400' }">
      <el-table-column type="index" label="序号" align="center" width="55" />
      <el-table-column prop="exportTime" label="导出时间" align="center">
        <template #default="scope">
          {{ dayjs(scope.row.create_time).format('YYYY-MM-DD') }}
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center">
        <template #default="_scope"> 导出 </template>
      </el-table-column>
      <el-table-column prop="content" label="数据类型" align="center" />
    </el-table>
    <el-pagination
      @current-change="handleNextPage"
      :current-page="expoetList?.current_page"
      :page-size="queryParams.limit"
      :total="expoetList?.total"
      background
      hide-on-single-page
      class="flex-1 items-end" />
    <el-dialog v-model="exportDialog" width="500" align-center :show-close="false" style="padding: 0">
      <div class="flex flex-col pb-4">
        <NavBar @handleClose="handleClose" title="流水数据导出" />
        <el-form :model="submitForm" class="px-6 pt-6 flex flex-col gap-6">
          <el-form-item label="选择时间:" required>
            <el-date-picker
              v-model="submitForm.startAndEndTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始月份"
              end-placeholder="结束月份" />
          </el-form-item>
          <el-form-item label="导出类型:" required>
            <el-select v-model="exportType" placeholder="请选择导出类型" @change="handleExportTypeChange">
              <el-option v-for="item in exportOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="账本类型:" required v-if="exportType == '1'">
            <el-select v-model="exportDataType" placeholder="请选择账本类型" @change="handleExportDataTypeChange">
              <el-option v-for="item in exportDataOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="导出数据:" required>
            <el-select v-model="selectDataName" placeholder="请选择导出数据" multiple>
              <el-option v-for="item in dataListOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="接收邮箱:" required>
            <el-input v-model="submitForm.email" placeholder="请输入接收邮箱" clearable />
          </el-form-item>
          <div class="flex justify-center" @click="handleSave">
            <div class="save-button">确定导出</div>
          </div>
        </el-form>
      </div>
    </el-dialog>
    <el-dialog v-model="shopDialog" width="500" align-center :show-close="false" style="padding: 0">
      <div class="flex flex-col pb-4">
        <NavBar @handleClose="handleShopClose" title="库存数据导出" />
        <el-form :model="submitForm" class="px-6 pt-6 flex flex-col gap-6">
          <el-form-item label="接收邮箱:" required>
            <el-input v-model="submitForm.email" placeholder="请输入接收邮箱" clearable />
          </el-form-item>
          <div class="flex justify-center" @click="handleShopSave">
            <div class="save-button">确定导出</div>
          </div>
        </el-form>
      </div>
    </el-dialog>
  </main>
</template>

<style lang="scss" scoped>
.save-button {
  @apply text-white px-16 py-3 rounded-md;
  background: linear-gradient(142deg, #ff9600 0%, #ffb242 100%);
}
.el-form-item {
  margin-bottom: 0px;
}
::v-deep .el-dialog__header {
  padding-bottom: 0 !important;
}
::v-deep .el-cascader {
  flex: 1;
}
</style>
